package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Menu;
import com.itheima.health.pojo.User;
import com.itheima.health.service.RoleService;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.LoginParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangmeng
 * @description
 * @date 2019/9/6
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    private static final String CURRENT_USER = "CURRENT_USER";
    @Reference
    private UserService userService;

    @Reference
    private RoleService roleService;


    /**
     * 根据用户名和密码登录
     *
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody LoginParam param) {
        log.info("[登录]data:{}", param);
        //rpc调用查询用户信息
        User user = userService.findByUsername(param.getUsername());
        //用户不存在或密码不匹配则登录失败
        if (null == user || !user.getPassword().equals(param.getPassword())) {
            return new Result(false, MessageConst.LOGIN_FAIL);
        }
        //用户信息写入 session
        request.getSession(true).setAttribute(CURRENT_USER, user);
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }

    /**
     * 登出
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/logout")
    public Result logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("[登出]……");
        //从session中删除用户
        request.getSession().removeAttribute(CURRENT_USER);
        //重定向到登录页
        response.sendRedirect("http://oms.health.itcast.com:8080/pages/login.html");
        return null;
    }


    /**
     * 获取当前登录用户名
     *
     * @return
     */
    @RequestMapping("/getUsername")
    public Result getUsername() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (null != principal && principal instanceof org.springframework.security.core.userdetails.User) {
            org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) principal;
            return new Result(true, MessageConst.GET_USERNAME_SUCCESS, user.getUsername());
        }
        return new Result(false, MessageConst.GET_USERNAME_FAIL);
    }

    @RequestMapping("/loginSuccess")
    public Result loginSuccess() {
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }

    @RequestMapping("/loginFail")
    public Result loginFail() {
        return new Result(false, "登录失败");
    }


    /**
     * 用户动态展示菜单
     *
     * @param username
     * @return
     */
    @RequestMapping("/getMenu")
    public Result getMenu(String username) {
        int userId = userService.selectByUserName(username);

        int roleId = roleService.selectByUserId(userId);

        List<Menu> menuList1 = userService.selectById(roleId);

        List<Menu> menuList2 = userService.selectMenuIdAndParentId(roleId);


        for (Menu menu : menuList1) {
            log.info("[动态菜单展示-一级菜单]", menu);
            List<Menu> menus = ziMenu(menu, menuList2);
            menu.setChildren(menus);
        }

        log.debug("[动态展示菜单数据]menuList1:{}", menuList1);
        return new Result(true, "登录成功", menuList1);
    }

    private List<Menu> ziMenu(Menu fuMenu, List<Menu> menuList) {
        List<Menu> ziList = new ArrayList<>();
        for (Menu menu : menuList) {
            if (fuMenu.getId().equals(menu.getParentMenuId())) {
                List<Menu> menus = ziMenu(menu, menuList);
                menu.setChildren(menus);
                ziList.add(menu);
            }
        }
        return ziList;
    }


    /**
     * 添加用户
     *
     * @param user
     * @param roleIds
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody User user, Integer[] roleIds) {
        log.info("[用户-添加]user:{},roles:{}", user, roleIds);
        //RPC请求添加
        userService.add(user, roleIds);
        return new Result(true, MessageConst.ACTION_SUCCESS);

    }

    /**
     * 分页查询
     *
     * @param queryPageBean
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(QueryPageBean queryPageBean) {
        log.info("[用户-分页查询]data:{}", queryPageBean);
        PageResult pageResult = userService.pageQuery(queryPageBean);
        return new Result(true, MessageConst.ACTION_SUCCESS, pageResult);

    }


    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/findById")
    public Result findById(Integer id) {
        log.info("[用户-根据id查询]id:{}", id);

        User user = userService.findById(id);
        return new Result(true, MessageConst.ACTION_SUCCESS, user);

    }


    /**
     * 根据用户id查询角色关联表数据
     *
     * @param id
     * @return
     */
    @GetMapping("/findRoleIdsByUserId")
    public Result findRoleIdsByUserId(Integer id) {
        log.info("[用户-根据用户id查询角色关联表数据]id:{}", id);

        List<Integer> roles = userService.findRoleIdsByUserId(id);
        return new Result(true, MessageConst.ACTION_SUCCESS, roles);

    }

    /**
     * 编辑
     *
     * @param user
     * @param roleIds
     * @return
     */
    @PostMapping("/edit")
    public Result edit(@RequestBody User user, Integer[] roleIds) {
        log.info("[用户-编辑]user:{},roleIds:{}", user, roleIds);

        userService.edit(user, roleIds);
        return new Result(true, MessageConst.ACTION_SUCCESS);
    }

    @PostMapping("/deleteById")
    public Result deleteById(Integer id) {
        log.info("[用户-根据id删除用户]id:{}", id);
        userService.deleteById(id);
        return new Result(true, MessageConst.ACTION_SUCCESS);
    }
}

